package com.lucifer.cloud.boot.blog.config;

import cn.hutool.json.JSONUtil;
import com.lucifer.cloud.boot.blog.domin.type.BlogConstant;
import com.lucifer.cloud.commons.model.Result;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;

/**
 * @author lucifer
 * @date 2024/1/25 11:48
 */
//@Slf4j
//@Component
public class OperatePermissionInterceptor implements HandlerInterceptor {


    @Resource
    private UserSystem userSystem;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        Long userId = userSystem.userId(request);
        if (Objects.isNull(userId)) {
            response.getWriter().write(JSONUtil.toJsonStr(Result.error(HttpStatus.UNAUTHORIZED.value(), BlogConstant.NOT_LOGIN)));
            return false;
        }
        Map<String, String[]> parameterMap = request.getParameterMap();
        if (Objects.nonNull(parameterMap.get(BlogConstant.USER_ID))) {
            String parameterUserId = parameterMap.get(BlogConstant.USER_ID)[0];
            Long $userId = Long.parseLong(parameterUserId);
            if (Objects.equals(userId, $userId)) {
                return true;
            }
        }
        response.getWriter().write(JSONUtil.toJsonStr(Result.error(HttpStatus.METHOD_NOT_ALLOWED.value(), BlogConstant.NOT_PERMISSION)));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) {

    }


}
